package com.brspace.qualitycontrol.utils;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;

/**
 * File类型转MultipartFile类型
 */
public class FileToMulFileUtil {

    public static MultipartFile FileToMultipartFile(File oneFile) throws IOException
    {
        FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(oneFile.toPath()), false, oneFile.getName(), (int) oneFile.length(), oneFile.getParentFile());
        InputStream input = null;
        OutputStream os = null;
        MultipartFile multipartFile = null;
        try {
            input = new FileInputStream(oneFile);
            os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            multipartFile = new CommonsMultipartFile(fileItem);
            input.close();
            os.close();
            return multipartFile;
        } catch (IOException ex) {
            throw new RuntimeException();
        } finally {
            if(input != null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
